package cn.xyfmzmy.eventloop;


/**
 * 定时任务对象，在Runnable基础上进行封装
 */
public class ScheduleTask implements Runnable,Comparable<ScheduleTask>{

    // 要执行的任务
    private final Runnable runnable;

    // 任务的执行时间
    private long deadline;

    // 任务的执行周期
    private long period;

    // 执行任务的eventLoop
    private MzmyEventLoop eventLoop;

    public ScheduleTask(Runnable runnable, long deadline, long period, MzmyEventLoop eventLoop) {
        this.runnable = runnable;
        this.deadline = deadline;
        this.period = period;
        this.eventLoop = eventLoop;
    }

    public long getDeadline() {
        return deadline;
    }

    @Override
    public void run() {
        try {
            // 执行任务
            runnable.run();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 更新执行时间，将任务放回队列中
            if(period > 0){
                deadline += period;
                eventLoop.getScheduleTaskQueue().offer(this);
            }
        }
    }

    @Override
    public int compareTo(ScheduleTask o) {
        // 时间小的，优先执行
        return Long.compare(this.deadline, o.deadline);
    }
}
